import PsMessageBox from '@/components/message-box/index'
import { logout } from '@/api/login'
import { getMemberInfo, checkStatus } from '@/api/user'
import { autoDrawCoupon } from '@/api/coupon'
import { batchDrawTrial } from '@/api/rights'
// import { getUserZbApi } from '@/api/zb'
import { kefuQQ, email } from '@/utils/costum'
import { isPassVersion, openKefu } from '@/utils/judge'
import { invokeAPi, invokeAsyncAPi } from '@/xz-fn.js'
import router, { menuRouter } from '@/router'
import i18n from '@/lang'
import store from '../../store'
import { getBackEndConfig, drawUserActivity } from '@/api/common'
const state = {
  token: '',
  hasLogin: false,
  hasPay: false,
  userInfo: {},
  userZb: 0,
  ACDialogType: '', // 账号对话框操作类型
  ACDialogQuery: {},
  confirm: false
}

const mutations = {
  SET_TOKEN (state, token) {
    state.token = token
  },
  SET_HASLOGIN (state, val) {
    state.hasLogin = val
  },
  SET_HASPAY (state, userInfo) {
    state.hasPay = userInfo
  },
  SET_USERINFO (state, userInfo) {
    state.userInfo = userInfo
  },
  SET_USERZB (state, zb) {
    state.userZb = zb || 0
  },
  SET_ACDIALOGTYPE (state, val) {
    state.ACDialogType = val
  },
  SET_ACDIALOGQUERY (state, data) {
    state.ACDialogQuery = data
  },
  SET_CONFIRM: (state, data) => {
    state.confirm = data
  }
}

const actions = {
  getToken ({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      invokeAsyncAPi('xz_get_token').then(res => {
        if (res) {
          commit('SET_TOKEN', res)
          resolve()
        } else {
          reject(res)
        }
      }).catch(e => {
        reject(e)
      })
    })
  },
  setToken ({ commit }, token) {
    commit('SET_TOKEN', token)
  },
  checkStatus ({ commit }, drawCoupon = false) {
    return new Promise((resolve, reject) => {
      checkStatus().then(() => {
        commit('SET_HASLOGIN', true)
        if (drawCoupon) {
          autoDrawCoupon({ show_pos: 'draw_center' }).finally(() => {
            resolve()
          })
        } else {
          resolve()
        }
      }).catch(e => {
        commit('SET_HASLOGIN', false)
        reject(e)
      })
    })
  },
  /**
   * 获取用户基础信息
   */
  getUserInfo ({ commit, dispatch, rootState }) {
    return new Promise((resolve, reject) => {
      getMemberInfo({}).then((res1) => {
        const data = res1.data || {}
        const buy_right_package = (data.buy_right_package || []).filter(item => {
          return rootState.system.info.allPackages.some(itemb => item.pkg_id === itemb)
        })
        data.buy_right_package = buy_right_package
        data.is_member = buy_right_package.some(item => item.unlimited || new Date(item.expire_at).getTime() / 1000 > data.server_time)
        invokeAPi('xz_update_user_info', JSON.stringify({
          username: data.Nickname,
          headimgurl: data.Portrait
        }))
        commit('SET_USERINFO', data)
        resolve(data)
      }).catch(e => {
        reject(e)
      })
    })
  },
  // getUserZb ({ commit, dispatch }) {
  //   getUserZbApi().then(res => {
  //     const data = res.data || {}
  //     commit('SET_USERZB', data.amount)
  //   })
  // },
  resetUserInfo ({ commit }, isCallXz = true) {
    const path = location.pathname
    const offsetPath = menuRouter.filter(item => !item.meta.whiteList)
    if (path !== '/usercenter' && offsetPath.some(item => item.path === path)) {
      router.push('/usercenter')
    }
    commit('SET_HASLOGIN', false)
    commit('SET_TOKEN', '')
    commit('SET_USERINFO', {})
    isCallXz && invokeAPi('xz_exit')
    PsMessageBox.close()
  },
  /**
   * 合并用户基础信息
   */
  mergeUserInfo ({ commit, state }, data = {}) {
    const userInfo = Object.assign({}, state.userInfo, data)
    invokeAPi('xz_update_user_info', JSON.stringify({
      username: userInfo.Nickname,
      headimgurl: userInfo.Portrait
    }))
    commit('SET_USERINFO', userInfo)
  },
  setUserInfo ({ commit, state }, data = {}) {
    commit('SET_USERINFO', data)
  },
  /**
   * 控制账号弹框操作类型
   * @param {string,Object} data - 类型
   * * forgetPwd 打开找回密码
   * * 为空，则关闭
   */
  setACDialogType ({ commit }, data) {
    let type
    let query
    if (typeof data === 'string') {
      type = data
    } else {
      type = data.type
      query = data.query
    }
    commit('SET_ACDIALOGTYPE', type)
    commit('SET_ACDIALOGQUERY', query || {})
    if (type && isPassVersion('3.0.4')) {
      invokeAPi('xz_switch_dialog', 'XZDesktopLogin', true, JSON.stringify({ type }))
    }
  },
  /**
   * 领取试用权益
   */
  drawTrial ({ rootState }) {
    return new Promise((resolve, reject) => {
      const arr = rootState.system.info.allPackages
      batchDrawTrial({ pkg_id: arr }, true).then(res => {
        const pkgids = (res.data.list || []).filter(it => {
          return it.sub_code === 'success'
        }).map(it => it.pkg_id)
        resolve(pkgids.join(','))
      }).catch(e => {
        resolve('')
      })
    })
  },
  /**
   * 领取场景送奖励
   */
  async drawPrize ({ rootState }) {
    if (store.getters.appInfo.allPackages.length < 1) return false
    const { data } = await getBackEndConfig({
      app_id: store.getters.appInfo.appID,
      version: store.getters.appInfo.version,
      union_id: store.getters.appInfo.channel,
      keyname: 'cjsjl'
    }).catch(() => null)
    if (data?.scene === 'login' && data.seckill_id) {
      const res = await drawUserActivity({ act_id: data.seckill_id }).catch(() => null)
      return res?.data?.sub_code === 'ok'
    }
    return false
  },
  login ({ commit, dispatch, rootState }, obj = {}) {
    const defaultType = rootState.system.info.isLXAnonymousLogin ? 'anonymousLogin' : 'wxLogin'
    if (!obj.type) {
      obj.type = localStorage.getItem('loginType') || defaultType
    }
    if (!['wxLogin', 'phoneLogin', 'emailLogin', 'anonymousLogin'].includes(obj.type)) {
      obj.type = defaultType
    }
    dispatch('setACDialogType', obj)
  },
  /**
   * 退出登录
   */
  logout ({ commit, dispatch, rootState }) {
    return logout({ uuid: rootState.system.info.uuid }).then(() => {
      commit('SET_TOKEN', '')
      dispatch('resetUserInfo')
    })
  },
  // eslint-disable-next-line
  setCustomerConfirm ({ state, commit }, message) {
    if (!state.confirm) {
      if (!isPassVersion('3.0.4')) {
        commit('SET_CONFIRM', true)
        setTimeout(() => {
          const overseas = store.getters.appInfo.appID === '124'
          const contact = overseas ? '' : ' QQ：' + kefuQQ
          PsMessageBox({
            dangerouslyUseHTMLString: true,
            footerHTMLString: overseas,
            footerMessage: overseas ? 'Email：' + email : '',
            // message: message + '<div style="color:#00BBD7;user-select:text;margin-top: 20px;">' + contact + '</div>',
            message: message + contact,
            confirmButtonText: i18n.t('kefu'),
            iconClass: 'error',
            center: true,
            showConfirmButton: !overseas,
            showCancelButton: !overseas,
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                // invokeAPi('xz_open_url', kefuUrl[String(store.getters.appInfo.appID)])
                openKefu()
              } else {
                commit('SET_CONFIRM', false)
                done()
              }
            }
          })
        }, 50)
      } else {
        commit('SET_CONFIRM', false)
        invokeAPi('xz_switch_dialog', 'XZDesktopFrozen', true)
      }
    }
  },
  setLogoutConfirm ({ state, dispatch, commit }, message) {
    if (!state.confirm) {
      commit('SET_CONFIRM', true)
      invokeAPi('xz_substat_action', 2423)
      setTimeout(() => {
        PsMessageBox({
          message,
          iconClass: 'error'
        }).then(() => {
          invokeAPi('xz_substat_action', 2424)
          if (process.env.VUE_APP_NAME === 'i18n') {
            router.push({
              path: '/login-page',
              query: {
                type: 'emailLogin'
              }
            })
          } else {
            dispatch('setACDialogType', 'phoneLogin')
          }
        }).finally(() => {
          commit('SET_CONFIRM', false)
        })
      }, 50)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
